package com.jia.search.utils;

import com.jia.search.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Component
public class HtmlParseUtil {

    public List<Content> parseJD(String keyword) throws Exception{
        // 1获取请求 https://search.jd.com/Search?keyword=java
        String url = "https://search.jd.com/Search?keyword="+keyword;
        // 2解析网页 返回的就是浏览器的Document对象 所有JavaScript干的 它都可以
        Document document = Jsoup.parse(new URL(url), 5000);
        // 所有js可以使用的它都可以用
        Element element = document.getElementById("J_goodsList");
        // 获取所有的li
        Elements lis = element.getElementsByTag("li");

        ArrayList<Content> goodList = new ArrayList<>();
        for (Element li : lis) {
            String img = li.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = li.getElementsByClass("p-price").eq(0).text();
            String title = li.getElementsByClass("p-name").eq(0).text();
            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);
            goodList.add(content);
        }
        return goodList;
    }
}
